<template>
    <view class="page">
        <view class="title-input">
            <view class="title">填写个人资料</view>
            <view class="title-name">
                <view class="title-icon">*</view>
                <van-field v-model="username" label="昵称" placeholder="请输入昵称" />
            </view>
            <view class="title-car">
                <span class="title-number">
                    <span class="title-icon">*</span>
                    <span class="title-text">车牌号码</span>
                </span>
                <span class="title-btn">
                    <van-icon name="plus" />
                    <span class="title-cartext" @tap.native="addCarnumber">添加车牌</span>
                </span>
            </view>
        </view>
        <view></view>
        <!-- 车牌号码输入框 -->
        <view :data-id="index" v-for="(item, idx) in plateNumbers" :key="item.i">
            <view class="carNumber">
                <!-- 车牌号头两位 -->
                <view class="carNumber-items">
                    <!-- <view class="carNumber-items-box" bindtap='openKeyboard'>
                <view class="carNumber-items-province carNumber-items-box-list">
                    {{carnum[0] || ''}}
                </view>
                <view class="carNumber-items-En carNumber-items-box-list">{{carnum[1] || ''}}</view>
            </view> -->
                    <!-- 常规 -->
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 0 ? 'active' : '')" :data-idx="idx" :data-index="0" @tap="openKeyboard">
                        {{ plateNumbers[idx][0] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 1 ? 'active' : '')" :data-idx="idx" :data-index="1" @tap="openKeyboard">
                        {{ plateNumbers[idx][1] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 2 ? 'active' : '')" :data-idx="idx" :data-index="2" @tap="openKeyboard">
                        {{ plateNumbers[idx][2] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 3 ? 'active' : '')" :data-idx="idx" :data-index="3" @tap="openKeyboard">
                        {{ plateNumbers[idx][3] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 4 ? 'active' : '')" :data-idx="idx" :data-index="4" @tap="openKeyboard">
                        {{ plateNumbers[idx][4] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 5 ? 'active' : '')" :data-idx="idx" :data-index="5" @tap="openKeyboard">
                        {{ plateNumbers[idx][5] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 6 ? 'active' : '')" :data-idx="idx" :data-index="6" @tap="openKeyboard">
                        {{ plateNumbers[idx][6] || '' }}
                    </view>
                    <!-- 新能源 -->
                    <view :class="'carNumber-item ' + (plateNumbers[idx][7] ? '' : 'carNumber-item-newpower')">
                        <view v-if="!plateNumbers[idx][7]" :data-idx="idx" :data-index="7" @tap="showPowerBtn">
                            <view class="carNumber-newpower-add">+</view>
                            <view>新能源</view>
                        </view>
                        <view v-if="plateNumbers[idx][7]" :data-idx="idx" :data-index="7" @tap="openKeyboard">
                            {{ plateNumbers[idx][7] }}
                        </view>
                    </view>
                    <view class="delete" :data-idx="idx" @tap="handleDelete">
                        <van-icon name="delete-o" size="40rpx" />
                    </view>
                </view>
            </view>
        </view>
        <!-- 虚拟键盘 -->
        <view class="keyboard" v-if="KeyboardState">
            <view class="keyboardClose">
                <view class="keyboardClose_btn" @tap="closeKeyboard">关闭</view>
            </view>
            <!-- 省份简写键盘 -->
            <view class="keyboard-item" v-if="plateIndex === 0">
                <view class="keyboard-line" v-for="(item, index) in provinces" :key="index">
                    <view class="keyboard-btn" :data-val="itemlist" :data-plate="plate" @tap="bindChoose" v-for="(itemlist, index1) in item" :key="index1">
                        {{ itemlist }}
                    </view>
                </view>
                <view class="keyboard-del" @tap="bindDelChoose">
                    <van-icon name="cross" style="margin-top: 10rpx" />
                    <!-- <text class="font_family icon-shanchu keyboard-del-font"></text> -->
                </view>
            </view>
            <!-- 车牌号码选择键盘 -->
            <view class="keyboard-item iscarnumber" v-else>
                <view class="keyboard-line" v-for="(item, index) in numbers" :key="index">
                    <view class="keyboard-btn" :data-val="itemlist" :data-plate="plate" @tap="bindChoose" v-for="(itemlist, index1) in item" :key="index1">
                        {{ itemlist }}
                    </view>
                </view>
                <view class="keyboard-del" @tap="bindDelChoose">
                    <van-icon name="cross" />
                </view>
            </view>
        </view>
        <view class="weui-cells__title">提示：暂时不支持临牌车辆</view>
        <!-- 提交车牌 -->
        <van-button type="info" class="carNumberBtn" @tap.native="submitNumber">保存</van-button>
    </view>
</template>

<script>
import util from './../../utils/util.js';
import api from './../../utils/api.js';
export default {
    data() {
        return {
            // 省份简写
            provinces: [
                ['京', '沪', '粤', '津', '冀', '晋', '蒙', '辽', '吉', '黑'],
                ['苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘'],
                ['桂', '琼', '渝', '川', '贵', '云', '藏'],
                ['陕', '甘', '青', '宁', '新']
            ],
            // 车牌输入
            numbers: [
                ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
                ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
                ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
                ['W', 'X', 'Y', 'Z', '港', '澳', '学']
            ],
            carnum: [],
            showNewPower: false,
            KeyboardState: false,
            username: '',
            plateNumbers: [['', '', '', '', '', '', '', '']],
            plate: 0,
            //第几个车牌
            plateIndex: -1,
            weixinCode: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        // console.log(wx.getStorageSync("phoneNumber"));
        this.getWeixincode();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getWeixincode();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function() {}
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        // 选中点击设置
        bindChoose(e) {
            var plate = this.plate;
            var index = this.plateIndex;
            var plateNumbers = this.plateNumbers;
            plateNumbers[plate][index] = e.target.dataset.val;
            this.setData({
                plateNumbers
            });

            if (index < 7) {
                index = index + 1;
                this.setData({
                    plateIndex: index
                });
            } else {
                this.setData({
                    KeyboardState: false,
                    plate: 0,
                    //第几个车牌
                    plateIndex: -1
                });
            }
        },

        bindDelChoose() {
            var plate = this.plate;
            var index = this.plateIndex;
            var plateNumbers = this.plateNumbers;
            plateNumbers[plate][index] = '';
            this.setData({
                plateNumbers
            });

            if (index > 0) {
                index = index - 1;
                this.setData({
                    plateIndex: index
                });
            }
        },

        showPowerBtn() {
            this.setData({
                showNewPower: true,
                KeyboardState: true
            });
        },

        closeKeyboard() {
            this.setData({
                KeyboardState: false
            });
        },

        openKeyboard(e) {
            this.setData({
                KeyboardState: true,
                plate: e.currentTarget.dataset.idx,
                plateIndex: e.currentTarget.dataset.index
            });
        },

        // 提交车牌号码
        // submitNumber() {
        //   if (this.data.carnum[6]) {
        //     // 跳转到tabbar页面
        //   }
        // },
        //添加车牌
        addCarnumber() {
            const plateNumberslength = this.plateNumbers.map((e) => e.join(''));

            for (let i = 0; i < plateNumberslength.length; i++) {
                if (plateNumberslength[i].length < 7) {
                    uni.showToast({
                        title: '请输入完整车牌',
                        icon: 'none'
                    });
                    return;
                }
            }

            let addItem = ['', '', '', '', '', '', '', ''];
            this.setData({
                plateNumbers: [...this.plateNumbers, addItem],
                KeyboardState: false
            });
        },

        //删除车牌号
        handleDelete(e) {
            if (e.currentTarget.dataset.idx == 0) {
                uni.showToast({
                    title: '请输入车牌号',
                    icon: 'none'
                });
                return;
            }

            const index = e.currentTarget.dataset.idx;
            this.plateNumbers.splice(index, 1);
            this.setData({
                plateNumbers: this.plateNumbers
            });
        },

        //注册
        setparkRegister() {
            const param = {
                loginName: uni.getStorageSync('phoneNumber'),
                name: this.username,
                plates: this.plateNumbers.map((e) => e.join(''))
            };

            if (uni.getStorageSync('shareId')) {
                param.originUnionId = uni.getStorageSync('shareId') || '';
            }

            if (uni.getStorageSync('activityCode')) {
                param.activityCode = uni.getStorageSync('activityCode') || '';
            }

            util.request(
                api.parkRegister,
                param,
                'POST' // "application/x-www-form-urlencoded"
            )
                .then((res) => {
                    if (res.code == 0) {
                        this.getparkLogin();
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    uni.showToast({
                        title: err,
                        icon: 'none'
                    });
                });
        },

        //登陆
        getparkLogin() {
            const param = {
                loginName: uni.getStorageSync('phoneNumber'),
                verificationType: 4,
                verificationCode: uni.getStorageSync('sms')
            };
            util.request(
                api.parkLogin2 +
                    '?loginName=' +
                    param.loginName +
                    '&verificationType=4' +
                    '&verificationCode=' +
                    param.verificationCode +
                    '&code=' +
                    this.weixinCode +
                    '&activityCode=' +
                    uni.getStorageSync('activityCode') ||
                    '' + '&shareId=' + uni.getStorageSync('shareId') ||
                    '',
                '',
                'POST' // "application/x-www-form-urlencoded"
            ).then((res) => {
                if (res.code == 0) {
                    uni.setStorage({
                        key: 'openId',
                        data: res.data.busiInfo.openId
                    }); //openId

                    uni.setStorage({
                        key: 'status',
                        data: true
                    }); //状态

                    uni.setStorage({
                        key: 'phoneNumber',
                        data: res.data.busiInfo.phoneNumber
                    }); //手机号

                    uni.setStorage({
                        key: 'name',
                        data: res.data.busiInfo.name
                    }); //姓名

                    uni.setStorage({
                        key: 'plateNos',
                        data: res.data.busiInfo.plateNos.map((e) => e).toString()
                    }); //用户车牌号

                    uni.setStorage({
                        key: 'faceImageUrl',
                        data: res.data.busiInfo.faceImageUrl
                    }); //头像

                    uni.setStorage({
                        key: 'AUTHORIZATION',
                        data: res.data.busiInfo.token
                    }); //token

                    uni.setStorage({
                        key: 'identityId',
                        data: res.data.busiInfo.identityId
                    }); //用户id

                    uni.setStorage({
                        key: 'unionId',
                        data: res.data.busiInfo.unionId
                    }); //用户id

                    uni.navigateTo({
                        url: '../success/index'
                    });
                } else if (res.busiCode === '00001') {
                    uni.setStorage({
                        key: 'status',
                        data: false
                    }); //状态

                    uni.navigateTo({
                        url: '../usermessage/index'
                    });
                } else if (res.busiCode === '04001') {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    this.getWeixincode();
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    this.getWeixincode();
                }
            });
        },

        // 保存  // 提交车牌号码
        submitNumber() {
            const that = this;

            if (that.username.replaceAll(' ', '')) {
                const plateNumberslength = that.plateNumbers.map((e) => e.join(''));

                for (let i = 0; i < plateNumberslength.length; i++) {
                    if (plateNumberslength[i].length < 7) {
                        uni.showToast({
                            title: '请输入完整车牌',
                            icon: 'none'
                        });
                        return;
                    }
                }

                that.setData({
                    KeyboardState: false
                });
                that.setparkRegister();
            } else {
                uni.showToast({
                    title: '请输入昵称',
                    icon: 'none'
                });
            } // wx.navigateTo({
            //   url: "../success/index"
            // });
        },

        getWeixincode() {
            let that = this;
            uni.login({
                success(res) {
                    console.log(res);
                    that.setData({
                        weixinCode: res.code
                    });
                }
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
